package team.szm.scd.database.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import team.szm.scd.database.entity.Department;
import team.szm.scd.database.entity.Register;
import team.szm.scd.database.properties.AppointmentTimeType;
import team.szm.scd.database.vo.RegisterVO;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Repository
public interface RegisterMapper extends BaseMapper<Register> {
    @Select("select count(*)\n" +
            "from register natural join doctor\n" +
            "where did = ${did}\n" +
            "  and appointment_day = '${date}' and appointment_time_type = ${period.value};")
    int registeredNumberInAPeriod
            (@Param("did") String doctorId,
             @Param("date") LocalDate date, @Param("period") AppointmentTimeType period);

    @Select("select count(uid) as count, dname, doctor.did, expert\n" +
            "from doctor\n" +
            "         left outer join\n" +
            "     (select *\n" +
            "      from register\n" +
            "      where (appointment_time_type = ${period.value}" +
            "            and appointment_day = '${date}')\n" +
            "     ) register\n" +
            "     on doctor.did = register.did\n" +
            "where hid = ${hid}\n" +
            "  and dpid = ${dpid}\n" +
            "  and (\n" +
            "        doctor.did in (\n" +
            "        select doctor_work_time.did\n" +
            "        from doctor_work_time\n" +
            "        where week_day = ${date.dayOfWeek.value}\n" +
            "          and ((start_time <= '${period.startTime}' and end_time >= '${period.startTime}')\n" +
            "            or\n" +
            "               (end_time >= '${period.endTime}' and start_time <= '${period.endTime}')))\n" +
            "    )\n" +
            "group by doctor.did\n" +
            "order by count(uid);\n")
    List<Map<String, Object>> doctorRegisterRemainInfo(
            @Param("hid") int hospitalId, @Param("dpid") int dpid,
            @Param("date") LocalDate date, @Param("period") AppointmentTimeType period);

    @Select("select rid as id, uid as userId, did as doctorId, " +
            "       rtime as registerTime, comeTime, appointment_time_type," +
            "       dpname as departmentName, hid as hospitalId," +
            "       uname as userName, dname as doctorName," +
            "       expert, appointment_day, address as userAddress, " +
            "       gender as userGender\n" +
            "from register natural join doctor natural join user natural join department\n" +
            " ${ew.customSqlSegment}")
    List<RegisterVO> registerVOListFromWrapper(@Param("ew")
                                      Wrapper<RegisterVO> wrapper);
}
